<template>
  <div>
    <!-- 折叠面板 -->
    <nut-collapse v-model="activeName" :accordion="true">
      <nut-collapse-item
        v-for="item in currentPageData"
        :key="item.ID"
        :title="item.leaveNameFull"
        :value="item.applyDate"
        :name="item.ID"
      >
        <view style="margin-bottom: 10px"> 开始时间: {{ item.dateStart }}</view>
        <view style="margin-bottom: 10px"> 结束时间: {{ item.dateEnd }} </view>
        <view style="margin-bottom: 10px"> 请假/加班天数: {{ item.dateCount }}</view>
        <view style="margin-bottom: 10px">请假原因: {{ item.leaveCause }}</view>
        <view style="margin-bottom: 10px">目前状态: {{ item.flowTag }}</view>

        <!-- <nut-button  color="#ce723c" size="small" @click="cancel(item.ID)">取消</nut-button> -->
        <nut-button
          v-if="['1', '2', '3', '4'].includes(item.state.toString())"
          color="#ce723c"
          size="small"
          @click="cancelRequest(item.leaveType)"
          >取消</nut-button
        >
      </nut-collapse-item>
    </nut-collapse>
  </div>
  <view style="position: fixed; bottom: 20px; left: 30px; z-index: 1000">
    <nut-pagination
      v-model="currentPage"
      :total-items="totalPage * itemsPerPage"
      :items-per-page="itemsPerPage"
      @change="handlePageChange"
    />
  </view>
</template>
<script>
import { reactive, ref, toRefs, computed } from "vue";
import Taro from "@tarojs/taro";
export default {
  setup() {
    const userData = Taro.getStorageSync("userData");
    const userid = userData.id;
    console.log("当前登录的用户id" + userData.id);
    const lastValidPage = ref(1);
    const activeName = ref(1);
    const dataList = ref([]);
    const currentPage = ref(1);
    const itemsPerPage = 5;
    var Type = 0;
    const select = async () => {
      const formData = {
        view: "V_GetLeaveRecord",
        userId: userData.id,
        depaCode: "string",
      };
      try {
        const response = await new Promise((resolve, reject) => {
          Taro.request({
            url: "https://sunyukq.transpheretms.com:8078/api/Select",
            method: "POST",
            data: formData,
            header: {
              "Content-Type": "application/json",
            },
            success: function (res) {
              if (res && res.statusCode === 200) {
                console.log("查询到数据");
                resolve(res.data);
              } else {
                console.log("查询失败");
                reject(new Error("查询失败"));
              }
            },
          });
        });
        dataList.value = response;
      } catch (error) {
        console.error("Error fetching data:", error);
      }
    };
    const currentPageData = computed(() => {
      const start = (currentPage.value - 1) * itemsPerPage;
      return dataList.value.slice(start, start + itemsPerPage);
    });
    const handlePageChange = (newPage) => {
      if (newPage > Math.ceil(dataList.value.length / itemsPerPage)) {
        Taro.showToast({
          title: "没有更多数据了",
          icon: "loading",
          duration: 2000,
        });
        currentPage.value = lastValidPage.value;
      } else {
        lastValidPage.value = newPage;
        currentPage.value = newPage;
      }
    };

    const totalPage = computed(() => {
      const totalPages = Math.ceil(dataList.value.length / itemsPerPage);
      return totalPages < 5 ? 5 : totalPages;
    });
    const cancelRequest = async (leaveType) => {
      const formData = {
        userId: userData.id,
        leaveType: leaveType,
      };

      try {
        const response = await new Promise((resolve, reject) => {
          Taro.request({
            url: "https://sunyukq.transpheretms.com:8078/api/leaveCancel",
            method: "POST",
            data: formData,
            header: {
              "Content-Type": "application/json",
            },
            success: function (res) {
              if (res && res.statusCode === 200) {
                Taro.showToast({
                  title: "取消成功",
                  icon: "success",
                  duration: 2000,
                });
                resolve(res.data);
                select();
              } else {
                reject(new Error("取消失败"));
              }
            },
          });
        });
      } catch (error) {
        console.error("Error during cancel request:", error);
        // 可能需要给用户一个错误提示
      }
    };

    select();
    return {
      totalPage,
      activeName,
      dataList,
      currentPage,
      currentPageData,
      handlePageChange,
      itemsPerPage,
      cancelRequest,
      lastValidPage,
    };
  },
};
</script>
